package com.bjsxt.buyaction.servivce.impl;

import com.bjsxt.buyaction.dao.ItemDao;
import com.bjsxt.buyaction.redisDao.RedisItemDao;
import com.bjsxt.buyaction.servivce.BuyActionService;
import com.bjsxt.livegoods.pojo.Item;
import com.bjsxt.livegoods.pojo.LivegoodsMessage;
import com.bjsxt.publisher.LivegoodsMessagePublisher;
import com.livegoods.commons.vo.LivegoodsResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;


/**
 * @ClassName : BuyActionServiceImpl
 * @Description :
 * @Author : ZWZ
 * @Date: 2021/8/27 9:34
 */
@Service
public class BuyActionServiceImpl implements BuyActionService {

    @Autowired
    private ItemDao itemDao;
    @Autowired
    private RedisItemDao redisItemDao;
    @Autowired
    private LivegoodsMessagePublisher livegoodsMessagePublisher;
    @Value("${livegoods.cache.names.item.prefix}")
    private String itemPrefix;
    @Value("${livegoods.cache.names.item.suffix}")
    private String itemSuffix;
    @Value("${livegoods.rabbit.buy.exchange}")
    private String exchange;
    @Value("${livegoods.rabbit.buy.routingKey}")
    private String routingKey;

    /**
     * 实现流程:
     * 1.  访问 redis，查询这个商品是否可购买
     * 2.  封装一个消息对象，发送消息到 MQ，并等待消费者的响应
     * 3. 根据消息消费者响应结果，返回操作结果
     *
     * @param id   商品主键
     * @param user 用户手机号
     * @return
     */
    @Override
    public LivegoodsResult buyAction(String id, String user) {
        String itemKey = itemPrefix + "::" + itemSuffix + "(" + id + ")";
        // 从 redis 中查询商品信息
        Item item = redisItemDao.get(itemKey);
        if (item.getRented()) {
            // 房租已出售，直接返回
            return LivegoodsResult.error("手慢了，已经被抢订，预订失败！");
        }
        LivegoodsMessage livegoodsMessage = new LivegoodsMessage(id, user);
        // 发送  mq
        Boolean messageResult =
                (Boolean) livegoodsMessagePublisher.sendMessageSync(exchange, routingKey, livegoodsMessage);
        if (messageResult) {
            return LivegoodsResult.ok("预订成功");
        }
        return LivegoodsResult.error("手慢了，已经被抢订，预订失败！");
    }

    @Override
    public LivegoodsResult bugTime(String itemId) {
        Item item = itemDao.findItemById(itemId);
        LivegoodsResult livegoodsResult = new LivegoodsResult();
        livegoodsResult.setStatus(LivegoodsResult.OK_CODE);
        livegoodsResult.setTime(item.getBuytime().getTime());
        return livegoodsResult;
    }
}
